<?php

/**
 * CtDocumento filter form.
 *
 * @package    ingenyo-biblio
 * @subpackage filter
 * @author     Ivan
 */
class CtDocumentoFormFilterCollection extends sfFormFilter
{

  public function configure()
  {
    $this->disableLocalCSRFProtection();
    if ($this->getOption('container',1)){
        $form = new CtDocumentoFormFilterCollection(null,array('container' => 0));
        $this->embedForm('filters', $form);
    }else{

        $subForm = new sfFormFilter();

        $ctDocumentoFormFilter = new CtDocumentoFormFilter(array(),array('is_the_last' => 1));
        $subForm->embedForm(0, $ctDocumentoFormFilter);

        $this->embedForm('custom', $subForm);

        //Busqueda por sucursal
        $sucursales = BbSucursalPeer::getSucursales();
        $sucursales[0] = 'Todos/as';
        $this->setWidget('sucursal', new sfWidgetFormChoice(array(
            'choices' => $sucursales,
          )));
        $this->setDefault('sucursal', 0);

        //Busqueda por Tipo de Documento
        $tipo_doc = CtValoresPeer::getTipificacion(sfConfig::get('app_tipificado_tipo_documento'));
        $tipo_doc[0] = 'Todos/as';
        $this->setWidget('tipo_doc', new sfWidgetFormChoice(array(
            'choices' => $tipo_doc,
          )));
        $this->setDefault('tipo_doc', 0);

        //Busqueda por Formato
        $formato = CtValoresPeer::getTipificacion(sfConfig::get('app_tipificado_formato'));
        $formato[0] = 'Todos/as';
        $this->setWidget('formato', new sfWidgetFormChoice(array(
            'choices' => $formato,
          )));
        $this->setDefault('formato', 0);

        $this->setWidget('valor_simple', new sfWidgetFormInput());
        $this->getWidget('valor_simple')->setAttribute('class','validate[required,minSize[3]]');
        $this->setWidget('tipo_busqueda', new sfWidgetFormInputHidden());
        //$this->setValidator('sucursal', new sfValidatorPass());
        //$this->setValidator('tipo_doc', new sfValidatorPass());
        //$this->setValidator('formato', new sfValidatorPass());

    }
  }

  public function getCriteriaFilter(){
    $tipo_busqueda = $this->taintedValues['tipo_busqueda'];

    if ($tipo_busqueda == 'simple') {
      return $this->crearCriteriaSimple();
    }else{
      return $this->crearCriteriaAvanzado();
    }
  }

  public function crearCriteriaSimple(){
    $c = new Criteria();

    $grupos = array(
      sfConfig::get('app_grupo_nombre_autor'),
      sfConfig::get('app_grupo_apellido_autor'),
      sfConfig::get('app_grupo_titulo'),
      sfConfig::get('app_grupo_tema'));

    $valor = $this->taintedValues['valor_simple'];
    $str = "";
    #$valor = trim($valor);
    $busqueda = $this->stripAccents($valor);
    #var_dump($busqueda);die();
    $table = 'dc1';
    $caracteristicas = CtCaracteristicaPeer::getChoiceByIdGrupoStr($grupos);
    
    $str = "(SELECT DISTINCT $table.idDocumento FROM CTDocumentoCaracteristica $table
    where $table.idCaracteristica IN ($caracteristicas) and $table.valorCaracteristica like '%".$busqueda."%')";
        


    if ($str != ""){
        $c->add(CTDocumentoPeer::ID, "CTDocumento.id in ($str) AND CTDocumento.fechaBaja is null" , Criteria::CUSTOM);

    }

    return $c;
  }

  public function crearCriteriaAvanzado(){
    $c = new Criteria();
    //hay que recuperar Documentos no documentos caracteristicas te agrego este join
    //$c->addJoin(CTDocumentoPeer::ID, CtDocumentoCaracteristicaPeer::IDDOCUMENTO);
    //$c->setDistinct();

    $custom_filters = $this->taintedValues['custom'];
    $str = "";
    foreach($custom_filters as $key => $custom)
    {
        //aca te agrege lo de los grupos en ves de las caracteristicas exactas
        if ($custom['valor'] != ""){
            $str .= $this->crearStr($custom, $key);
            if ($key != (count($custom_filters)-1)){
                $str .= ' '.$custom['logico'].' ';
            }
        }

    }

    if ($str != ""){
        $str_second = "";
        if ($this->taintedValues['sucursal'] != 0) {
          $str_second = '('.CtDocumentoPeer::getDocumentosByIdSucursal($this->taintedValues['sucursal']).')';
        }
    
        if ($this->taintedValues['tipo_doc'] != 0) {
          if ($str_second != '') {
            $str_second .= ' AND ';
          }
          $str_second .= '('.CtCaracteristicaPeer::getChoiceByIdGrupoQuery($this->taintedValues['tipo_doc']).')';
        }
    
        if ($this->taintedValues['formato'] != 0) {
          if ($str_second != '') {
            $str_second .= ' AND ';
          }
          $str_second .= '('.CtCaracteristicaPeer::getChoiceByIdGrupoQuery($this->taintedValues['formato']).')';
        }
        
        if ($str_second == ''){
          $c->add(CTDocumentoPeer::ID, "CTDocumento.id in ($str)" , Criteria::CUSTOM);
        }else{
          $c->add(CTDocumentoPeer::ID, "CTDocumento.id in ($str) AND $str_second AND CTDocumento.fechaBaja IS NULL", Criteria::CUSTOM);
        }
        
    }
    $test = $c->toString();
    return $c;
  }


  public function crearStr($custom, $key){
    $busqueda_sin_espacios = trim($custom['valor']);
    $busqueda  = $this->stripAccents($busqueda_sin_espacios);
    $table = 'dc'.$key;
    $grupo = CtCaracteristicaPeer::getChoiceByIdGrupoStr($custom['caracteristica']);
    $str = "(SELECT DISTINCT $table.idDocumento FROM CTDocumentoCaracteristica $table
    where $table.idCaracteristica IN ($grupo) and $table.valorCaracteristica like '%".$busqueda."%')";
    return $str;
  }

  public function addCustom($next, $is_the_last){
    $filters = $this->embeddedForms['filters'];
    $custom = $filters->embeddedForms['custom'];
    $ctDocumentoFormFilter = new CtDocumentoFormFilter(array(),array('is_the_last' => $is_the_last));
    $custom->embedForm($next,$ctDocumentoFormFilter);
    $filters->embedForm('custom',$custom);
    $this->embedForm('filters',$filters);
  }

function stripAccents($text){
  $text = htmlentities($text, ENT_QUOTES, 'UTF-8');
		$text = strtolower($text);
		$patron = array (
			// Espacios, puntos y comas por guion
			#'/[\., ]+/' => '-',
 
			// Vocales
			'/&agrave;/' => 'a',
			'/&egrave;/' => 'e',
			'/&igrave;/' => 'i',
			'/&ograve;/' => 'o',
			'/&ugrave;/' => 'u',
 
			'/&aacute;/' => 'a',
			'/&eacute;/' => 'e',
			'/&iacute;/' => 'i',
			'/&oacute;/' => 'o',
			'/&uacute;/' => 'u',
 
			'/&acirc;/' => 'a',
			'/&ecirc;/' => 'e',
			'/&icirc;/' => 'i',
			'/&ocirc;/' => 'o',
			'/&ucirc;/' => 'u',
 
			'/&atilde;/' => 'a',
			'/&etilde;/' => 'e',
			'/&itilde;/' => 'i',
			'/&otilde;/' => 'o',
			'/&utilde;/' => 'u',
 
			'/&auml;/' => 'a',
			'/&euml;/' => 'e',
			'/&iuml;/' => 'i',
			'/&ouml;/' => 'o',
			'/&uuml;/' => 'u',
 
			'/&auml;/' => 'a',
			'/&euml;/' => 'e',
			'/&iuml;/' => 'i',
			'/&ouml;/' => 'o',
			'/&uuml;/' => 'u',
 
			// Otras letras y caracteres especiales
			'/&aring;/' => 'a',
			'/&ntilde;/' => 'n',
 
			// Agregar aqui mas caracteres si es necesario
 
		);
 
		$text = preg_replace(array_keys($patron),array_values($patron),$text);
		return $text;

}
  
  
}
